const dayjs = require('dayjs')
const dbUtil = require('../util/dbutil')
const { genToken } = require('../util/jwt')
const { AssertUtils } = require('../util/utils')
/**
 * 
 * @param {string} username 用户名
 * @param {string} password 密码
 * @returns 
 */
const login = async (username, password) => {
    let user = await getUserByUsername(username)
    AssertUtils.ObjectNotEmpty(user, "账号或密码错误")
    AssertUtils.isTrue(user.password == password, "账号或密码错误")
    return genToken({ id: user.id })
}

/**
 * 注册
 * @param {string} username 用户名
 * @param {string} password 密码
 * @param {string} name 密码
 * @returns 
 */
const register = async (username, password, phone, name) => {
    let user = await getUserByUsername(username)
    AssertUtils.isTrue(user == null, "账号已存在")
    return await dbUtil.exec('insert into user (username, password, phone,name) values (?,?,?,?)', [username, password, phone, name])
}

/**
 * 验证码登录
 * @param {string} phone 手机号码
 * @param {string} code 验证码
 * @returns 
 */
const smsLogin = async (phone, code) => {
    let user = await getUserByPhone(phone)
    AssertUtils.ObjectNotEmpty(user, "用户不存在")
    let smsCode = await dbUtil.getRow("select * from sms_code where phone = ? and expire_time > ? and status = 0 and code = ?", [phone, dayjs().subtract(1, 'minute').toDate(), code])
    AssertUtils.ObjectNotEmpty(smsCode, "验证码不存在")
    await dbUtil.exec('update sms_code set status = 1 where id = ?', [smsCode.id])
    return genToken({ id: user.id })
}

/**
 * 找回密码
 * @param {string} phone 手机号码
 * @param {string} code 验证码
 * @returns 
 */
const repass = async (phone, code, password) => {
    let user = await getUserByPhone(phone)
    AssertUtils.ObjectNotEmpty(user, "用户不存在")
    let smsCode = await dbUtil.getRow("select * from sms_code where phone = ? and expire_time > ? and status = 0 and code = ?", [phone, dayjs().subtract(1, 'minute').toDate(), code])
    AssertUtils.ObjectNotEmpty(smsCode, "验证码不存在")
    await dbUtil.exec('update sms_code set status = 1 where id = ?', [smsCode.id])
    return await dbUtil.exec('update user set password = ? where id = ?', [password, user.id])
}
/**
 * 通过用户名获取用户
 * @param {string} username 用户名
 * @returns 用户
 */
const getUserByUsername = (username) => {
    return dbUtil.getRow(`select * from user where username = ?`, [username])
}
/**
 * 通过手机获取用户
 * @param {string} phone 手机
 * @returns 用户
 */
const getUserByPhone = (phone) => {
    return dbUtil.getRow(`select * from user where phone = ?`, [phone])
}
/**
 * 通过用户id获取用户
 * @param {int} 用户id 
 * @returns 用户
 */
const getUserById = (id) => {
    return dbUtil.getRow(`select * from user where id = ?`, [id])
}

module.exports = {
    login,
    smsLogin,
    repass,
    register,
    getUserByUsername,
    getUserById,
    getUserByPhone
}